#include<iostream>
#include<assert.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstring>
using namespace std;
int main()
{
    //第一步：创建管道文件，打开读写端
    int fds[2];
    int n = pipe(fds);
    assert(n == 0);
    //第二步：fork
    pid_t id = fork();
    assert(id >= 0);
    if(id == 0)
    {
        //子进程进行读取
        close(fds[1]);
        //子进程的通信代码
        while(1)
        {
            //sleep(1);
            char buffer[1024];
            ssize_t s = read(fds[0], buffer, sizeof(buffer) - 1);
            if(s > 0)
            {
                buffer[s] = 0;
            }
            cout << "Get Message#" << buffer << "my pid:" << getpid() << endl;
            if(s == 0)
            {
                break;
            }
        }
        //子进程
        close(fds[0]);
        exit(0);
    }
    //父进程进行写入
    close(fds[0]);
    //父进程的通信代码
    const char *s = "I am father.";
    int cnt = 0;
    while(1)
    {
        cnt++;
        char buffer[1024];
        snprintf(buffer, sizeof buffer, "parent->child:%s[%d][%d] ", s, cnt, getpid());
        //写入
        write(fds[1], buffer, strlen(buffer));
        cout << "count:" << cnt << endl;
        sleep(1);
        //break;
    }
    //父进程关闭读端
    close(fds[1]);

    int status = 0;
    n = waitpid(id, &status, 0);//进程等待，获取子进程pid
    cout << "pid->" << n << ":" << (status & 0x7f) << endl;
    assert(n == id);
    

    //0:嘴巴，读取
    //1:钢笔，输入
    return 0;
}
